﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Linq;

namespace Songhay.Extensions
{

    /// <summary>
    /// Extensions of <see cref="Microsoft.VisualStudio.TestTools.UnitTesting.TestContext"/>
    /// </summary>
    public static class TestContextExtensions
    {
        /// <summary>
        /// Removes the previous test results.
        /// </summary>
        /// <param name="context">The context.</param>
        public static void RemovePreviousTestResults(this TestContext context)
        {
            if (context == null) return;

            var predicate = FuncSeed.True<FileInfo>()
                .And(f => f.Extension != ".ldf")
                .And(f => f.Extension != ".mdf");

            var directory = Directory.GetParent(context.TestDir);
            directory.EnumerateFiles()
                    .Where(predicate)
                    .OrderByDescending(f => f.LastAccessTime).Skip(1)
                    .ForEachInEnumerable(f => f.Delete());
            directory.EnumerateDirectories()
                    .OrderByDescending(d => d.LastAccessTime).Skip(1)
                    .ForEachInEnumerable(d => d.Delete(true));
        }
    }
}